function [ latencies ] = selectMarkerLatencies( EEG, markersToFind, preBoundary, postBoundary, includeStart, includeEnd )
%SELECTMARKERLATENCIES Select markers from an eeglab EEG set between boundaries.
%   Usage: to select ambiguous sphere left responses:
%      selectMarkerLatencies(EEG, {'R-SC-L'}, {'S-SC-A'}, {'S-Rest-10'}, false, true)
%   Will select latencies of all R-SC-L markers that exist between S-SC-A
%   and S-Rest-10 (or the end of the EEG data).
%   - includeStart: The beginning of the datafile will be treated as an extra preBoundary
%   - includeEnd: The beginning of the datafile will be treated as an extra postBoundary
%   Usage: to select all markers of a certain type, without boundaries:
%      selectMarkerLatencies(EEG, {'S-SC-L' 'S-SC-R'}, {}, {}, true, true)

%% Find all pre and post markers
allPreMarkers = false(1,length(EEG.event));
for m = preBoundary
    allPreMarkers = allPreMarkers | strcmp(m, {EEG.event(:).type});
end
allPostMarkers = false(1,length(EEG.event));
for m = postBoundary
    allPostMarkers = allPostMarkers | strcmp(m, {EEG.event(:).type});
end

%% Detect the regions of valid markers
allValidMarkers = false(1,length(EEG.event));
validRegion = logical(includeStart);
for i = 1:length(allValidMarkers)
    if allPostMarkers(i)
        allValidMarkers(i) = false;
        validRegion = false;        
    elseif allPreMarkers(i)
        allValidMarkers(i) = false;
        validRegion = true;
    else
        allValidMarkers(i) = validRegion;
    end
end
if ~logical(includeEnd) && validRegion % The end should not be included, but there is no postBoundary marker..
    lastPostMarkerIdx = find(allPostMarkers, 1, 'last' ); % Find the last postBoundary marker
    allValidMarkers(lastPostMarkerIdx:end) = false;
end

%% Find all matching markers
allMatchingMarkers = false(1,length(EEG.event));
for m = markersToFind
    allMatchingMarkers = allMatchingMarkers | strcmp(m, {EEG.event(:).type});
end

%% Get the valid matching markers
allValidMatchingMarkers = allMatchingMarkers & allValidMarkers;
% t = {EEG.event(:).type}
% x = [allPreMarkers;allValidMarkers;allPostMarkers;allMatchingMarkers;allValidMatchingMarkers]
vmmIdx = find(allValidMatchingMarkers);
latencies = zeros(length(vmmIdx),1);
disp('Selected markers:');
for i = 1:length(latencies)
    latencies(i) = EEG.event(vmmIdx(i)).latency;
    marker = EEG.event(vmmIdx(i)).type;
    disp(['   #' int2str(vmmIdx(i)) ' <' marker '> @ ' int2str(latencies(i)) ' (' num2str(latencies(i)/EEG.srate, '%4.1f') 's)' ]);
end


end

